<template>
    <div>
        <SuperTable ref="table" path="/admin/role/index" :params="params" :columns="columns">
            <Button slot="header-left" type="primary" @click="showModal = true">新增角色</Button>
        </SuperTable>
        <Modal
            v-model="showModal"
            :title="form.id ? '编辑角色' : '新增角色'"
            :width="480"
            @on-cancel="handleCancel"
        >
            <Form ref="form" :model="form" :rules="rules" :label-width="80" style="padding-right: 40px;">
                <FormItem label="角色名称" prop="name">
                    <Input v-model="form.name" />
                </FormItem>
                <FormItem label="所属权限" required>
                    <div style="padding: 0 15px; height: 330px; border: 1px solid #dcdee2; border-radius: 5px; line-height: 22px; overflow: hidden; overflow-y: auto;">
                        <Tree :data="ruleCloneNodes" show-checkbox multiple></Tree>
                    </div>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button :disabled="submiting" @click="handleCancel">取消</Button>
                <Button type="primary" :loading="submiting" @click="handleSubmit">提交</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
import SuperTable from '@/components/utils/super-table.vue';
export default {
    components: {
        SuperTable
    },
    data() {
        return {
            submiting: false,
            showModal: false,
            ruleNodes: [],
            ruleCloneNodes: [],
            params: {
                page: 1,
                pageSize: 10
            },
            form: {
                id: '',
                name: '',
                rules: []
            },
            rules: {
                name: [
                    {required: true, message: '请输入角色名称', trigger: 'blur'}
                ]
            },
            columns: [
                {
                    title: '角色名称',
                    key: 'name'
                },
                {
                    title: '权限节点',
                    key: 'rules'
                },
                {
                    title: '创建时间',
                    width: 160,
                    key: 'created_at'
                },
                {
                    title: '操作',
                    width: 160,
                    render: (h, params) => {
                        return h('div', [
                            h('Button', {
                                props: {
                                    type: 'success',
                                    size: 'small',
                                    disabled: params.row.id === 1 ? true : false
                                },
                                on: {
                                    click: () => {
                                        this.form.id = params.row.id;
                                        this.form.name = params.row.name;
                                        let ids = params.row.rules.split(',') || [];
                                        this.form.rules = ids.map(item => Number(item));
                                        this.handleSetNodeCheckeds();
                                        this.showModal = true;
                                    }
                                }
                            }, '编辑'),
                            h('Button', {
                                props: {
                                    type: 'error',
                                    size: 'small',
                                    disabled: params.row.id === 1 ? true : false
                                },
                                style: {
                                    marginLeft: '10px'
                                },
                                on: {
                                    click: () => {
                                        this.handleDelete(params.row);
                                    }
                                }
                            }, '删除')
                        ])
                    }
                }
            ]
        }
    },
    mounted() {
        this.init();
    },
    methods: {
        init() {
            // 权限节点
            this.$ajax.get('/admin/rule/index').then(res => {
                this.ruleNodes = res || [];
                this.handleSetNodeCheckeds();
            }).catch(() => {
                // todo
            })
        },
        handleSetNodeCheckeds() {
            let ids = this.form.rules;
            this.ruleCloneNodes = this.ruleNodes.map(item => {
                let obj = {
                    title: item.title,
                    id: item.id,
                    pid: item.pid,
                    checked: false,
                    expand: true,
                    selected: false
                }
                if(item._children && item._children.length > 0) {
                    obj.children = item._children.map(child => {
                        return {
                            title: child.title,
                            id: child.id,
                            pid: child.pid,
                            checked: ids.indexOf(child.id) !== -1 ? true : false,
                            expand: true,
                            selected: false
                        };
                    })
                }
                return obj;
            })
        },
        handleGetNodes() {
            let ids = [];
            this.ruleCloneNodes.forEach(item => {
                if(item.checked) {
                    ids.push(item.id);
                }
                if(item.children) {
                    item.children.forEach(child => {
                        if(child.checked) {
                            if (ids.indexOf(child.pid) === -1){
                                ids.push(child.pid);//返回父级
                            }
                            ids.push(child.id);
                        }
                    })
                }
            })
            return ids;
        },
        handleSubmit() {
            if(this.submiting) return false;
            this.$refs.form.validate((valid) => {
                if(valid) {
                    const { form } = this;
                    let params = {
                        name: form.name
                    }
                    let rules = this.handleGetNodes();
                    if(rules.length === 0) {
                        this.$Message.error('请选择所属权限');
                        return false;
                    }
                    params.rules = rules.join(',');
                    if (form.id) {
                        this.$ajax.put('/admin/role/update/'+form.id, params).then(res => {
                            this.$Message.success('编辑成功');
                            this.handleCancel();
                            this.$refs.table.reload();
                            this.submiting = false;
                        }).catch(err => {
                            this.submiting = false;
                            this.$Message.error(err.message || '提交失败');
                        })
                    }else{
                        this.$ajax.post('/admin/role/save', params).then(res => {
                            this.$Message.success('添加成功');
                            this.handleCancel();
                            this.$refs.table.init();
                            this.submiting = false;
                        }).catch(err => {
                            this.submiting = false;
                            this.$Message.error(err.message || '提交失败');
                        })
                    }
                }
            })
        },
        handleDelete(row) {
            this.$Modal.confirm({
                title: "操作提示:",
                content: `<p>您确定要删除角色‘${row.name}’吗?</p>`,
                onOk: () => {
                    const msg = this.$Message.loading({
                        content: '正在提交删除',
                        duration: 0
                    });
                    this.$ajax.delete('/admin/role/delete', {params: {ids: [row.id]}}).then(() => {
                        msg();
                        this.$Message.success('删除成功');
                        this.$refs.table.reload();
                    }).catch(err => {
                        msg();
                        this.$Message.error(err.message || '删除失败');
                    })
                }
            });
        },
        handleCancel() {
            this.showModal = false;
            setTimeout(() => {
                this.form.id = '';
                this.form.name = '';
                this.form.rules = [];
                this.handleSetNodeCheckeds();
            }, 300)
        }
    }
}
</script>